<template>
  <div class="uploadVideo">
    <!-- 顶部导航栏 -->
    <Navbar title="发布视频" placeholder>
      <template #left>
        <div class="left" @click="handleBackClick">
          <Icon name="zuojiantou" color="#fff" size="20" />
        </div>
      </template>
    </Navbar>

    <!-- 视频上传区域 -->
    <div class="uploadVideo_Video">
      <!-- 视频预览区 -->
      <div class="uploadVideo_Video_top" v-if="!hasVideo">
        <!-- 未上传视频时：显示上传入口 -->
        <input type="file" accept="video/*" class="uploadVideo_Video_Input" @change="handleFileChange" />
        <Icon name="shangchuanshipin" color="#28b8db" size="25" />
        <span class="uploadVideo_Video_span">点击上传或点击下方输入 URL，推荐使用 URL</span>
      </div>
      <div class="uploadVideo_Video_top" v-else>
        <!-- 已上传视频：显示预览 -->
        <!-- <CustomVideo :src="videoPreviewUrl" :showProgress="false" /> -->
        <video :src="videoPreviewUrl" controls></video>
      </div>

      <!-- 表单区域 -->
      <div class="uploadVideo_Video_bottom">
        <div class="uploadVideo_Video_bottom_form">
          <!-- 视频链接输入（本地上传可不填） -->
          <div class="uploadVideo_Video_bottom_form_item">
            <input type="text" id="videoUrl" placeholder="请输入视频链接（如本地上传可不填）" v-model="videoUrl" />
          </div>

          <!-- 封面链接输入（本地上传时默认使用第一帧，此字段可选） -->
          <div class="uploadVideo_Video_bottom_form_item" v-if="!hasVideo">
            <input type="text" id="wrapUrl" placeholder="请输入封装链接（如本地上传默认第一帧）" v-model="wrapUrl" />
          </div>

          <!-- 视频描述 -->
          <div class="uploadVideo_Video_bottom_form_item">
            <input type="text" id="videoDesc" placeholder="请输入视频描述" v-model="videoDesc" />
          </div>

          <!-- 操作按钮 -->
          <div class="uploadVideo_Video_bottom_form_item">
            <div class="uploadVideo_Video_bottom_form_item_preview">预览</div>
            <div class="uploadVideo_Video_bottom_form_item_submit" @click="handleSubmitClick">
              发布视频
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import Navbar from '@/components/common/Navbar.vue'
import Icon from '@/components/common/Icon.vue'
// import CustomVideo from '@/components/Common/CustomVideo/index.vue'
import { useUserStore } from '@/stores/userinfo'
import { uploadVideoAPI, uploadCoverAPI, publishVideoAPI } from '@/api/Uploadvideo'
// 引入弹窗组件
import { showDialog } from '@/utils/showDialog'
import { Toast } from '@/utils/showtoast'


// ======================
// 全局状态 & 路由
// ======================
const router = useRouter()
const userStore = useUserStore()
const userId = userStore.userInfo?.userId

// ======================
// 表单数据
// ======================
const videoPreviewUrl = ref('') // 视频预览 URL（用于本地文件预览）
const uploadedVideoFile = ref(null) // 用户选择的本地视频文件
const hasVideo = computed(() => !!uploadedVideoFile.value) // 是否已选择本地视频
const videoDesc = ref('') // 视频描述
const videoUrl = ref('') // 视频链接（若使用 URL 上传）
const wrapUrl = ref('') // 封面链接（本项目中本地上传自动截取，此字段暂未使用）

// ======================
// 事件处理
// ======================

/**
 * 返回上一页
 */
const handleBackClick = () => {
  router.go(-1)
}

/**
 * 处理本地视频文件选择
 */
const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    uploadedVideoFile.value = file
    const url = URL.createObjectURL(file)
    videoPreviewUrl.value = url
    videoUrl.value = url // 本地文件也赋值给 videoUrl（仅用于预览，实际上传走文件）
  } else {
    uploadedVideoFile.value = null
    videoPreviewUrl.value = ''
    videoUrl.value = ''
  }
}

/**
 * 提交发布视频（仅支持本地上传）
 */

const handleSubmitClick = async () => {
  showDialog({
    title: '发布视频',
    message: '是否确认发布该视频？',
    onConfirm: () => {
      console.log('用户点击了确定，开始发布...')
      performPublish()
    },
    onCancel: () => {
      console.log('用户取消发布')

    }
  })
}
const performPublish = async () => {
  // 校验：必须上传本地视频
  if (!uploadedVideoFile.value) {
    showDialog({
      title: '错误',
      message: '请先上传视频文件',
    })
    return
  }

  if (!userId) {
    showDialog({
      title: '错误',
      message: '用户未登录，请先登录',
    })
    return
  }

  try {
    // ======================
    // Step 1: 上传视频文件
    // ======================
    const videoFormData = new FormData()
    videoFormData.append('videoPath', uploadedVideoFile.value)

    const videoRes = await uploadVideoAPI(videoFormData)
    if (!videoRes?.filename) {
      throw new Error('视频上传失败：未返回文件名')
    }

    // 提取 videoId（去掉扩展名）
    const videoId = videoRes.filename.includes('.')
      ? videoRes.filename.split('.').slice(0, -1).join('.')
      : videoRes.filename

    // 构造视频访问 URL（根据后端实际返回调整）
    const videoPathUrl = videoRes.videoPath || `http://43.138.15.137:3000/assets/videoPath/${videoRes.filename}`

    // ======================
    // Step 2: 截取封面（第一帧）
    // ======================
    let coverBlob
    try {
      coverBlob = await getVideoCover(uploadedVideoFile.value)
    } catch (err) {
      console.error('封面截取失败:', err)
      showDialog({
        title: '错误',
        message: '封面生成失败，请重试',
      })
      return
    }

    // ======================
    // Step 3: 上传封面
    // ======================
    const coverFormData = new FormData()
    coverFormData.append('videoId', videoId)
    coverFormData.append('videoCover', coverBlob, 'cover.jpg')

    const coverRes = await uploadCoverAPI(coverFormData)
    console.log('封面上传响应:', coverRes)

    const videoCoverUrl = coverRes.videoCover || `http://43.138.15.137:3000/assets/videoCover/${videoId}.jpg`

    // ======================
    // Step 4: 发布视频元数据
    // ======================
    const publishData = {
      videoId,
      videoPath: videoPathUrl,
      videoCover: videoCoverUrl,
      videoDesc: videoDesc.value || '无描述'
    }

    const publishRes = await publishVideoAPI(userId, publishData)
    if (publishRes.code !== 200) {
      throw new Error(publishRes.message || '发布失败')
    }

    // ======================
    // 成功处理
    // ======================
    Toast('视频发布成功', {
      position: 'bottom'
    })
    router.push({ name: 'my' })

  } catch (error) {
    console.error('发布流程出错:', error)
    showDialog({
      title: '错误',
      message: `发布失败：${error.message}`,
    })
  }
}

/**
 * 从视频文件中截取第一帧作为封面
 * @param {File} videoFile - 用户选择的视频文件
 * @returns {Promise<Blob>} 封面图片 Blob
 */
function getVideoCover(videoFile) {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video')
    video.muted = true
    video.preload = 'metadata'
    const url = URL.createObjectURL(videoFile)
    video.src = url

    // 错误处理
    video.onerror = () => {
      URL.revokeObjectURL(url)
      reject(new Error('无法加载视频文件'))
    }

    // 视频元数据加载完成
    video.onloadedmetadata = () => {
      // 跳转到 0.1 秒避免黑屏
      video.currentTime = 0.1
    }

    // 跳转完成，截图
    video.onseeked = () => {
      const canvas = document.createElement('canvas')
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      const ctx = canvas.getContext('2d')
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

      // 转为 JPEG Blob
      canvas.toBlob(
        (blob) => {
          URL.revokeObjectURL(url) // 释放内存
          blob ? resolve(blob) : reject(new Error('截图失败'))
        },
        'image/jpeg',
        1 // 质量 100%
      )
    }
  })
}
</script>

<style lang="scss" scoped>
.uploadVideo_Video {
  height: calc(100vh - 46px);
  background-color: #161622;

  .uploadVideo_Video_top {
    width: 100%;
    height: 40%;
    background-color: #000;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10px;

    video {
      width: 100%;
      height: 100%;
      object-fit: contain;
      background-color: #000;
    }

    .uploadVideo_Video_Input {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      cursor: pointer;
    }

    .uploadVideo_Video_span {
      font-size: 12px;
      color: #fff;
      font-weight: bold;
      cursor: pointer;
    }
  }

  .uploadVideo_Video_bottom {
    padding: 10px;
    width: 100%;
    height: 60%;
    display: flex;
    align-items: center;
    justify-content: center;

    .uploadVideo_Video_bottom_form {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      gap: 20px;

      .uploadVideo_Video_bottom_form_item {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 60px;

        input {
          width: 100%;
          height: 100%;
          padding: 0 10px;
          font-size: 12px;
          color: #fff;
          background: transparent;
          border: 1px solid #393b44;
          border-radius: 5px;
          font-weight: bold;
          box-sizing: border-box;
        }

        .uploadVideo_Video_bottom_form_item_preview,
        .uploadVideo_Video_bottom_form_item_submit {
          width: 50%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 14px;
          font-weight: bold;
          border-radius: 5px;
          cursor: pointer;
        }

        .uploadVideo_Video_bottom_form_item_preview {
          background-color: #393b44;
        }

        .uploadVideo_Video_bottom_form_item_submit {
          background-color: #f9355f;
        }
      }
    }
  }
}
</style>